//店铺数据模块
import {getShopSellerReq, getGoodsListReq, getRatingsReq} from '@/api/shop'
const state = {
  shopData: {},
  goodsList: [], //商品列表
  ratingList: [], //评论列表
}

//getters
const getters = {
  navList(state) {
    return state.goodsList.map(v => v.name)
  },

  //筛选满意和不满意
  //满意
  goodRateList(state) {
    return state.ratingList.filter(v => {
      return v.score > 3
    })
  },
  //不满意
  badRateList(state) {
    return state.ratingList.filter(v => {
      return v.score <= 3
    })
  },
  //筛选出 count>0的食品
  filterFoodsList(state) {
    let temp = []
    state.goodsList.forEach(good => {
      good.foods.forEach(food => {
        if (food.count > 0) {
          temp.push(food)
        }
      })
    })
    return temp
  },

  //计算购物车总数量
  filterTatalCount(state, getters) {
    return getters.filterFoodsList.reduce((total, cur) => {
      return total + cur.count
    }, 0)
  },

  //计算总金额
  fliterTotalAmount(state, getters) {
    return getters.filterFoodsList.reduce((total, cur) => {
      return total + cur.price * cur.count
    }, 0)
  },
}

const mutations = {
  SET_SHOPINFO(state, data) {
    state.shopData = data
  },
  SET_GOODS_lIST(state, data) {
    state.goodsList = data
  },
  SET_RATING_LIST(state, data) {
    state.ratingList = data
  },
}

const actions = {
  //获取店铺数据
  A_getShopInfo({commit}) {
    return new Promise(async resolve => {
      let res = await getShopSellerReq()
      //解构数据
      let {data} = res.data
      //数据赋值
      commit('SET_SHOPINFO', data)
      resolve()
    })
  },
  //获取商品列表数据
  A_getGoodsData({commit}) {
    return new Promise(async resolve => {
      //发送请求
      let res = await getGoodsListReq()
      //解构参数
      let {code, data} = res.data
      //判断
      if (code === 0) {
        //处理数据  给每个食品增加一个count
        data.forEach(v => {
          v.foods.forEach(subV => {
            //给每个食品新增一个count字段
            subV.count = 0
          })
        })
        //数据赋值
        commit('SET_GOODS_lIST', data)
        resolve()
      }
    })
  },

  //获取评论列表数据
  A_getRatingsReq({commit}) {
    return new Promise(async resolve => {
      //发送请求
      let res = await getRatingsReq()
      //结构数据
      let {errno, data} = res.data

      //判断
      if (errno === 0) {
        commit('SET_RATING_LIST', data)
        resolve()
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}
